import os
import shutil

import facade
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.tools.BaseString import BaseString

from id_encode import GetLngid

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
configfile = BaseDir.get_new_path(curpath, "db.ini")
sPath = BaseDir.get_new_path(curpath, "template")
db3dir = BaseDir.get_new_path(TopPath, "download", "ebmbook_mirrorgdit", "download", "db3")
BaseDir.create_dir(db3dir)


class CreateZTDB(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger, cursorsnum=1)
        self.templatedb3 = BaseDir.get_new_path(sPath, "zt_template.db3")
        self.new_db3_path = self.copyTempDB3(self.templatedb3, db3dir)
        self.db3_zt = facade.Sqlite3Utiles(logger=self.logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'zt_mirrorgditebmbook_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def setztdb3(self):
        sql = "select * from book where stat=0"
        rows = self.mysqlutils.SelectFromDB(sql)
        Listpara = []
        for row in rows:
            rawid = row["rawid"].strip()
            title = row["title"].strip()
            url = "http://10.10.177.1:8081/" + row["url"].strip()
            author = row["author"].replace(",", ";").strip()
            author = BaseString.cleanSemicolon(author)
            isbn = row["isbn"].replace("-", "").strip()
            isbn = isbn.replace("/", ";")
            isbn = BaseString.cleanSemicolon(isbn)
            pisbn = ""
            if isbn.find("(Print)") > -1:
                pisbn = isbn.split("(Print)")[0].strip()
                isbn = isbn.split("(Print)")[1].replace("(Online)", "").strip()

            press = row["press"].strip()
            downdate = row["downdate"].strip()
            formats = row["formats"].strip()
            if formats == "PDF":
                if_pdf_fulltext = "1"
            else:
                if_pdf_fulltext = "0"
            coverstat = row["coverstat"]



            cover = ""
            if int(coverstat) == 1:
                cover = "/smartlib/ebmbook_mirrorgdit/" + rawid.lower() + ".jpg"

            sub_db_id = "00121"
            product = "MIRROREBMTS"
            sub_db = "GDIT"
            provider_zt = "ebmbook_mirrorgdit"
            provider = "HULIANJINQIAO"

            bacth = MDateTimeUtils.get_today_date_strings() + "00"
            type_ = "1"
            medium = "2"
            provider_url = provider_zt + "@" + url
            provider_id = provider_zt + "@" + rawid
            date = "1900"
            date_created = "19000000"
            country = "CN"
            language = "EN"

            lngid = GetLngid(sub_db_id, rawid)

            Listpara.append((lngid, rawid, title, author, isbn, press, country, language, cover, provider_zt, bacth,
                             type_, medium, provider_url, provider_id, date, date_created, if_pdf_fulltext, pisbn))

        sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`,`creator`,`identifier_eisbn`,`publisher`,`country`,`language`,`cover`,`provider`,`batch`,`type`,`medium`,`provider_url`,`provider_id`,`date`,`date_created`,`if_pdf_fulltext`,`identifier_pisbn`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
        self.db3_zt.ExeSqlliteMany(sql, Listpara)

    def updatesqlstat(self):
        sql = "update book set stat=1 where stat=0"
        self.mysqlutils.ExeSqlToDB(sql)


if __name__ == "__main__":
    ztdb = CreateZTDB()
    ztdb.setztdb3()
    # 确认db3的量和数据没有问题后更新mysql
    #ztdb.updatesqlstat()
